package movieGandalf.dbParser;

public class ParserTools {
	public static String getMovieName(String line){
		int i=0;
		int len = line.length();
		
		for (i=0;i<len;i++){
			if (line.charAt(i)=='\t' || line.charAt(i)=='(')
				break;
		}
		if (i==len)
			return "";
		
		String shortName = line.substring(0,i).trim();
		
		return shortName;
	}
	
	public static String getIMDBName(String line){
		int i=0,j=0;
		int len = line.length();
		int l = 0;
		boolean isNumber = true;
		
		for (i=0;i<len;i++){
			if (line.charAt(i)=='\t')
				break;
		}
		if (i==len)
			return "";
		
		String movie = line.substring(0,i).trim();
		String[] parts = movie.split(" ");
		for (i=parts.length-1;i>=0;i--){
			//if (!parts[i].equals("(V)") && !parts[i].equals("(TV)") && !parts[i].equals("{{SUSPENDED}}") && !parts[i].equals("(uncredited)"))
			l = parts[i].length();
			if (l<2 || parts[i].charAt(0)!='(' || parts[i].charAt(l-1)!=')')
				continue;
			
			isNumber = true;
			for (j=1;j<parts[i].length()-1;j++){
				if (!Character.isDigit(parts[i].charAt(j)) && parts[i].charAt(j)!='?'){
					isNumber = false;
					break;
				}
			}
			
			if (isNumber)
				break;
		}
		
		if (i<0)
			return movie;
		
		String imdbName = "";
		for (j=0;j<=i;j++){
			if (j!=0)
				imdbName += " ";
			imdbName += parts[j];
		}
		
		i = movie.length() - 1;
		while (movie.charAt(i)==')' && i>=1 && !Character.isDigit(movie.charAt(i-1)) && movie.charAt(i-1)!='?'){
			for (;i>=0 && movie.charAt(i)!='(';i--);
			movie = movie.substring(0,i+1);
		}
		
		return imdbName;
	}
	
	public static Short getYear(String line){
		int i=0;
		int end = line.length() - 1;
		
		for (;end>=0 && !Character.isDigit(line.charAt(end)) && line.charAt(end)!='?';end--);
		
		for (i=end;i>=0 && (Character.isDigit(line.charAt(i)) || line.charAt(i)=='?');i--);
		
		if (i<0)
			return -1;
		
		String year = line.substring(i+1,end+1);
		if (year.contains("?"))
			year = "0";
		
		return new Short(Short.parseShort(year));
	}
}
